<?php
/**
 * App_Ro
 *
 * @package    App
 * @subpackage App_Ro
 */

/**
 * ユーザートップ用エントリーリソース
 *
 * @category   BEAR
 * @package    App
 * @subpackage App_Ro
 * @author     $Author: koriyama $ <anonymous@example.com>
 * @version    SVN: Release: $Id: Top.php 360 2009-09-20 12:35:42Z koriyama $
 */
class App_Ro_Entry_Top extends App_Ro
{
    /**
     * テーブル名
     *
     * @var string
     */
    protected $_table = App_Ro::TABLE_ENTRY;

    /**
     * コンストラクタ
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
    }

    /**
     * インジェクタ
     */
    public function onInject()
    {
        parent::onInject();
        $this->_queryConfig['pager'] = 0;
        $this->_queryConfig['perPage'] = 3;
        $this->_query = BEAR::dependency('BEAR_Query', $this->_queryConfig, false);
    }

    /**
     * リソース読み込み
     *
     * <pre>
     * user_idを指定しないとpublic ,
     * user_idを指定すると自分とフォロー中のエントリーを取得
     * </pre>
     */
    public function onRead($values)
    {
        $andFollow =  isset($values['user_id']) ?
        'AND (users.id in (SELECT followers.follow_id FROM followers WHERE followers.user_id = :user_id AND followers.deleted_at IS NULL) OR users.id = :user_id)' : '';
        $sql = "SELECT entries.created_at,
        entries.body,
        entries.reply_user_id,
        users.user_name,
        users.image,
        entries.id as entry_id,
        users.id as user_id,
        entries.deleted_at
        FROM users INNER JOIN entries ON users.id = entries.user_id
        WHERE entries.deleted_at IS NULL
        {$andFollow}
        ORDER BY entries.id DESC";
        $result = $this->_query->select($sql, $values);
        return $result;
    }
}